"""
简单的web服务端
"""
import re
from socket import *
from select import select


class WebServer:
    def __init__(self, host, port, html):
        self.host = host
        self.port = port
        self.html = html
        self.address = (self.host, self.port)
        self.rlist = []
        self.sock = self.__create_socket()

    # 准备tcp套接字
    def __create_socket(self):
        sock = socket()
        sock.bind(self.address)
        sock.setblocking(False)
        return sock

    # 处理浏览器连接
    def __connect(self):
        conn, addr = self.sock.accept()
        print("Connect from ", addr)
        conn.setblocking(False)
        self.rlist.append(conn)  # 增加监控对象

    # 启动服务
    def start(self):
        self.sock.listen(5)
        print("Listen the port %d" % self.port)
        self.rlist.append(self.sock)
        while True:
            rs, ws, xs = select(self.rlist, [], [])
            for r in rs:
                if r is self.sock:
                    self.__connect()
                else:
                    self.__handle(r)

    # 具体处理HTTP请求
    def __handle(self, conn):
        # 接收http请求
        request = conn.recv(10204).decode()
        # 解析出请求内容
        try:
            info = re.search(r"[A-Z]+\s+(/\S*)", request).group(1)
            print("请求内容：", info)
        except Exception:
            return
        else:
            # 组织响应
            self.__response(conn, info)

    def __response(self, conn, info):

        if info == '/':
            filename = self.html + '/index.html'
            print(filename)
        else:
            filename = self.html + info
        try:
            file = open(filename, 'rb')
        except:
            response = "HTTP/1.1 404 Not Found\r\n"
            response += "Content-Type:text/html\r\n"
            response += "\r\n"
            response = response.encode()
        else:
            response = "HTTP/1.1 200 OK\r\n"
            response += "Content-Type:text/html\r\n"
            response += "\r\n"
            response = response.encode() + file.read()
        finally:
            conn.send(response)


if __name__ == '__main__':
    # 参数？
    httpd = WebServer(host='0.0.0.0', port=8001, html='static')
    httpd.start()
